package com.web.controller.web;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.common.collect.Lists;
import com.web.dao.LogLoginMapper;
import com.web.dao.SysMenuMapper;
import com.web.domain.Dict;
import com.web.domain.MRole;
import com.web.domain.MUser;
import com.web.domain.WebResponse;
import com.web.entity.*;
import com.web.service.RoleService;
import com.xkk.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xukk
 * @date 2017/9/6
 */
@Slf4j
@Controller
public class LoginController {
    @Autowired
    DefaultKaptcha captchaProducer;
    @Autowired
    RedisTemplate<String, String> redisTemplate;
    @Autowired
    private LogLoginMapper logLoginMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private RoleService roleService;

    public MUser getCurrentUser() {
        MUser user = (MUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        return user;
    }



    @GetMapping("index")
    public String index(Model model) {
        MUser mUser = getCurrentUser();
        LogLoginExample logLoginExample = new LogLoginExample();
        logLoginExample.createCriteria().andUserIdEqualTo(mUser.getId()).andSignTypeEqualTo("login");
        PageHelper.startPage(1, 2);
        boolean isAgent = false;
        for (MRole r : mUser.getRoles()) {
            if ("3".equals(r.getRoleId())) {
                isAgent = true;
            }
        }
        logLoginExample.setOrderByClause("sign_time desc");
        PageInfo pageInfo = new PageInfo(logLoginMapper.selectByExample(logLoginExample));
        if (pageInfo.getList() != null && pageInfo.getList().size() == 2) {
            model.addAttribute("logLogin", pageInfo.getList().get(1));
            if (isAgent) {
                model.addAttribute("isAgent", 1);
            } else {
                model.addAttribute("isAgent", 0);
            }

        } else{
            LogLogin logLogin = new LogLogin();
            logLogin.setSignTime(new Date());
            model.addAttribute("logLogin", logLogin);
        }
        return "index";
    }

    @GetMapping("err/{path}")
    public String Error404(@PathVariable String path) {
        return path;
    }

    /**
     * 登录地址
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/login",
            method = RequestMethod.GET)
    public String login(Model model, HttpServletRequest request) {
        model.addAttribute("error", request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION"));
        return "login";
    }

    @RequestMapping(value = "/default/captcha_image")
    public ModelAndView getKaptchaImage(HttpServletRequest request,
                                        HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control",
                "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();
        System.out.println("capText: " + capText);
        try {
            String uuid = UUIDUtil.getUUID();
            redisTemplate.boundValueOps(Dict.Constants.REDIS_NAMESPACE_KAPACHA + uuid).set(capText, 60 * 5, TimeUnit.SECONDS);
            Cookie cookie = new Cookie("captchaCode", uuid);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 5);
            response.addCookie(cookie);
        } catch (Exception e) {
            log.warn("/capthca_image:error:" + e.getMessage());
            return null;
        }

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }



    @GetMapping("getMenus")
    @ResponseBody
    public WebResponse getMenus() {
        MUser mUser = getCurrentUser();
        List<SysMenu> sysMenus = sysMenuMapper.selectByExample(new SysMenuExample());
        List<SysMenu> menu1 = Lists.newArrayList();
        List<SysMenu> menu2 = Lists.newArrayList();
        List<SysMenu> menu3 = Lists.newArrayList();
        List<Role> roles = Lists.newArrayList();
        if (mUser.getRoles() != null) {
            mUser.getRoles().forEach(value -> {
                Role role = new Role();
                role.setId(Long.valueOf(value.getRoleId()));
                roles.add(role);
            });
        }
        roleService.getRoleDetail(roles);
        for (Role role : roles) {
            List<SysMenu> m1 = role.getMenus();
            if (m1 != null) {
                for (SysMenu m2 : m1) {
                    Boolean flag = false;
                    for (SysMenu m3 : menu1) {
                        if (m3.getId().equals(m2.getId())) {
                            flag = true;
                        }
                    }
                    if (!flag) {
                        menu1.add(m2);
                    }
                }
            }
        }
        for (SysMenu sysMenu : sysMenus) {
            for (SysMenu sysMenu1 : menu1) {
                if (sysMenu1.getId().equals(sysMenu.getId())) {
                    menu2.add(sysMenu);
                }
            }
        }
        for (SysMenu sysMenu : menu2) {
            if (sysMenu.getEnabled() && sysMenu.getLevel() == 0) {
                sysMenu = recycle(sysMenu, menu2);
                menu3.add(sysMenu);
            }
        }
        return WebResponse.ok("", menu3);
    }

    public SysMenu recycle(SysMenu obj, List<SysMenu> sysMenus) {
        if (obj.getHasNext()) {
            if (obj.getMenus() == null) {
                obj.setMenus(Lists.newArrayList());
            }
            for (SysMenu s2 : sysMenus) {
                if (s2.getEnabled() && s2.getPid().equals(obj.getId())) {
                    s2 = recycle(s2, sysMenus);
                    obj.getMenus().add(s2);
                }
            }
        }
        return obj;

    }
}
